<!-- ToDify弹窗 -->
<div class="modal fade" id="singleToDifyModal" tabindex="-1" aria-labelledby="singleToDifyModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="singleToDifyModalLabel">推送到Dify知识库</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="singleToDifyForm">
          <input type="hidden" id="singleDifyDocumentId" name="document_id" value="">
          
          <div class="mb-3">
            <label for="difyApiServer" class="form-label">Dify API服务器地址</label>
            <input type="text" class="form-control" id="difyApiServer" value="{{ dify_api_server }}" readonly>
          </div>
          
          <div class="mb-3">
            <button type="button" class="btn btn-outline-primary w-100" id="testConnectionBtn">
              <i class="fas fa-plug me-2"></i>测试连接
            </button>
          </div>
          
          <div class="mb-3">
            <label for="difyKnowledgeBase" class="form-label">选择知识库</label>
            <select class="form-select" id="difyKnowledgeBase" name="dataset_id" required>
              <option value="" selected disabled>请先测试连接</option>
            </select>
          </div>
        </form>
        
        <!-- 推送结果反馈 -->
        <div id="singlePushError" class="alert alert-danger mt-3" style="display: none;"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="singlePushToDifyBtn">
          <i class="fas fa-cloud-upload-alt me-2"></i>推送
        </button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // DOM元素缓存
  const modal = document.getElementById('singleToDifyModal');
  const testBtn = document.getElementById('testConnectionBtn');
  const pushBtn = document.getElementById('singlePushToDifyBtn');
  const errorDiv = document.getElementById('singlePushError');
  const kbSelect = document.getElementById('difyKnowledgeBase');
  
  // 显示错误信息
  const showError = msg => {
    errorDiv.textContent = msg;
    errorDiv.style.display = 'block';
  };
  
  // Toast通知函数
  const toast = (type, msg) => {
    try {
      window.showToast(type, msg);
    } catch (e) {
      console.log(`通知(${type}): ${msg}`);
    }
  };
  
  // 更新文档状态
  const updateDocStatus = (id, status) => {
    const selector = `[data-bs-target="#singleToDifyModal"][data-document-id="${id}"]`;
    const statusEl = document.querySelector(selector)?.closest('.document-item')?.querySelector('.dify-push-status');
    
    if (!statusEl) return;
    
    statusEl.classList.remove('status-chunked', 'status-processing', 'status-pending');
    
    if (status === 'pushing') {
      statusEl.classList.add('status-processing');
      statusEl.textContent = '推送中';
    } else if (status === 'pushed') {
      statusEl.classList.add('status-chunked');
      statusEl.textContent = '已推送';
    } else {
      statusEl.classList.add('status-pending');
      statusEl.textContent = '未推送';
    }
  };
  
  // 弹窗显示事件
  modal.addEventListener('show.bs.modal', function(event) {
    // 获取文档ID
    const docId = event.relatedTarget.getAttribute('data-document-id');
    document.getElementById('singleDifyDocumentId').value = docId;
    
    // 重置UI状态
    errorDiv.style.display = 'none';
    testBtn.innerHTML = '<i class="fas fa-plug me-2"></i>测试连接';
    testBtn.classList.remove('btn-success', 'btn-danger');
    testBtn.classList.add('btn-outline-primary');
    testBtn.disabled = false;
    kbSelect.innerHTML = '<option value="" selected disabled>请先测试连接</option>';
  });
  
  // 测试连接
  testBtn.addEventListener('click', function() {
    testBtn.disabled = true;
    testBtn.innerHTML = '<i class="fas fa-circle-notch fa-spin me-1"></i>测试连接中...';
    errorDiv.style.display = 'none';
    
    fetch('/chunklab/dify/test-connection')
      .then(res => res.json())
      .then(data => {
        if (data.status === 'success') {
          testBtn.innerHTML = '<i class="fas fa-check-circle me-1"></i>连接成功';
          testBtn.classList.replace('btn-outline-primary', 'btn-success');
          
          // 加载知识库
          kbSelect.innerHTML = '<option value="" selected disabled>加载中...</option>';
          return fetch('/chunklab/dify/knowledge-bases').then(res => res.json());
        } else {
          showError(data.message || '连接失败');
          testBtn.innerHTML = '<i class="fas fa-times-circle me-1"></i>连接失败';
          testBtn.classList.replace('btn-outline-primary', 'btn-danger');
          return Promise.reject();
        }
      })
      .then(data => {
        if (data && data.status === 'success') {
          kbSelect.innerHTML = '<option value="" selected disabled>请选择知识库</option>';
          
          (data.data.data || []).forEach(kb => {
            const option = document.createElement('option');
            option.value = kb.id;
            option.textContent = kb.name;
            kbSelect.appendChild(option);
          });
        } else {
          showError('获取知识库列表失败');
          kbSelect.innerHTML = '<option value="" selected disabled>加载失败</option>';
        }
      })
      .catch(() => {})
      .finally(() => setTimeout(() => testBtn.disabled = false, 1000));
  });
  
  // 推送到Dify
  pushBtn.addEventListener('click', function() {
    const docId = document.getElementById('singleDifyDocumentId').value;
    
    // 检查知识库选择
    if (!kbSelect.value) {
      showError('请选择知识库');
      return;
    }
    
    // 更新状态为推送中
    updateDocStatus(docId, 'pushing');
    
    // 禁用按钮
    pushBtn.disabled = true;
    pushBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>推送中...';
    errorDiv.style.display = 'none';
    
    // 提交请求
    const formData = new FormData();
    formData.append('dataset_id', kbSelect.value);
    
    fetch(`/chunklab/dify/push/${docId}`, {
      method: 'POST',
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      // 恢复按钮状态
      pushBtn.disabled = false;
      pushBtn.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>推送';
      
      if (data.status === 'processing') {
        // 关闭弹窗和清理背景
        const modalInstance = bootstrap.Modal.getInstance(modal);
        modalInstance.hide();
        
        setTimeout(() => {
          // 清理模态框背景
          document.body.classList.remove('modal-open');
          document.querySelector('.modal-backdrop')?.remove();
          
          // 显示开始通知
          toast('info', '文档推送已开始，后台处理中...');
          
          // 检查推送状态，设置轮询间隔
          let statusCheckInterval = setInterval(() => {
            fetch(`/chunklab/dify/status/${docId}`)
              .then(res => res.json())
              .then(statusData => {
                if (statusData.status === 'pushed') {
                  clearInterval(statusCheckInterval);
                  toast('success', '文档推送成功');
                  updateDocStatus(docId, 'pushed');
                }
              })
              .catch(() => {});
          }, 3000);
          
          // 60秒后清除轮询（如果还没完成）
          setTimeout(() => clearInterval(statusCheckInterval), 60000);
        }, 300);
      } else {
        showError(data.message || '推送失败');
      }
    })
    .catch(error => {
      pushBtn.disabled = false;
      pushBtn.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>推送';
      showError('推送失败: ' + error.message);
    });
  });
});
</script> 